package com.xyb.controller;

import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xyb.entity.GiteeAccessToken;
import com.xyb.entity.GiteeUser;
import com.xyb.entity.Result;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("test")
public class GiteeController {
    // gitee 客户端id 和 客户端密钥
    private static String clientId = "2ad6db7e1cef9a3c85adbdb2b9a69dab1da5757b76975a2805641488e5ce009c";
    private static String clientSecret = "73a22ea4ee3703f3966572a2889541ad92430063e0eeba052f1a28e21051aaff";

    // gitee 用户授权认证页面
    private static String authUrl = "https://gitee.com/oauth/authorize";

    // gitee 授权之后重定向地址
    private static String redirectUri = "http://127.0.0.1:8080/test/info";

    // gitee 获取 token 请求地址
    private static String tokenUrl = "https://gitee.com/oauth/token";

    @GetMapping("url")
    public Result getUrl() {
        StringBuilder sb = new StringBuilder();
        /**
         * 构建一个如下的 url
         * https://gitee.com/oauth/authorize?client_id=2ad6db7e1cef9a3c85adbdb2b9a69dab1da5757b76975a2805641488e5ce009c&redirect_uri=http://127.0.0.1:8080/test/info&response_type=code&state=HelloWorld
         */
        sb.append(authUrl).append("?")
                .append("client_id").append("=").append(clientId).append("&")
                .append("redirect_uri").append("=").append(redirectUri).append("&")
                .append("response_type").append("=").append("code").append("&")
                .append("state").append("=").append("HelloWorld");
        String url = sb.toString();
        Result result = new Result();
        result.setCode(200);
        result.setMsg("success");
        result.setData(url);
        return result;
    }

    @GetMapping("info")
    public Result getUserInfo(String code, String state) throws JsonProcessingException {
        System.out.println("code = " + code);
        System.out.println("state = " + state);

        /**
         * 使用 HuTool 工具类构建 post 请求 https://hutool.cn/
         */
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("redirect_uri", redirectUri);
        paramMap.put("code", code);
        paramMap.put("client_id", clientId);
        paramMap.put("client_secret", clientSecret);

        /**
         * 发起一个 post 请求
         */
        String respBody = HttpUtil.post(tokenUrl, paramMap);
        System.out.println("respBody = " + respBody);

        /**
         * 解析返回的数据,取出 access_token
         * {"access_token":"5568eb932eca72f697e893f4a2851c8d","token_type":"bearer","expires_in":86400,"refresh_token":"720b47425c061029ec7659efefd75bb8165389ec637a51932774af4b91dec52c","scope":"user_info","created_at":1631779380}
         * access_token = 5568eb932eca72f697e893f4a2851c8d
         */
        ObjectMapper om = new ObjectMapper();
        GiteeAccessToken accessToken = om.readValue(respBody, GiteeAccessToken.class);
        String access_token = accessToken.getAccess_token();
        System.out.println("access_token = " + access_token);

        /**
         * 获取到的 令牌token 就可以请求 Gitee 的 api了
         * 例如 获取授权用户的资料, https://gitee.com/api/v5/user?access_token=5568eb932eca72f697e893f4a2851c8d
         */
        String getUserInfoUrl = "https://gitee.com/api/v5/user" + "?" + "access_token" + "=" + access_token;
        String userInfo = HttpUtil.get(getUserInfoUrl);
        System.out.println("userInfo = " + userInfo);

        GiteeUser giteeUser = om.readValue(userInfo, GiteeUser.class);
        System.out.println("giteeUser.name = " + giteeUser.getName());

        //这里可以返回一个和前端约定的值,让前端控制页面跳转,也可以后端返回一个 301重定向
        Result result = new Result();
        result.setCode(200);
        result.setMsg("success");
        return result;
    }

}
